<template>

  <!--  卡片区域  -->
  <n-card>
    <!--  工具栏  -->
    <n-space justify="end" style="padding-bottom: 15px;">
      <!--  新建按钮  -->
      <n-button @click="showModal = true" type="info" style="width: 80px; height:30px;">
        <n-icon size="18">
          <add/>
        </n-icon>
        新建
      </n-button>
      <!--  刷新  -->
      <n-tooltip trigger="hover">
        <template #trigger>
          <n-button text style="font-size: 20px; width: 22px; height: 32px;" @click="refresh">
            <n-icon>
              <refresh-sharp/>
            </n-icon>
          </n-button>
        </template>
        <span>刷新</span>
      </n-tooltip>
      <!--  密度  -->
      <n-popselect v-model:value="densityValue" :options="densityOptions" trigger="click">
        <n-tooltip trigger="hover">
          <template #trigger>
            <n-button text style="font-size: 20px; width: 22px; height: 32px; margin-left: 11px">
              <n-icon>
                <auto-fit-height20-regular/>
              </n-icon>
            </n-button>
          </template>
          <span>密度</span>
        </n-tooltip>
      </n-popselect>
      <!--  列设置  -->
      <n-tooltip tirgger="hover">
        <template #trigger>
          <n-popover teigger="click" placement="bottom-end">
            <template #trigger>
              <n-button text style="font-size: 20px; width: 22px; height: 32px; margin-bottom: 2px; margin-left: 11px">
                <n-icon>
                  <Settings20Regular/>
                </n-icon>
              </n-button>
            </template>
            <template #header>
              <n-checkbox label="列展示" v-model:checked="allChecked" @update:checked="allChange" />
            </template>
            <n-space vertical>
              <n-checkbox v-for="item in checkboxList" :key="item.name" :label="item.name" v-model:checked="item.checked" @update:checked="itemChange" />
            </n-space>
          </n-popover>
        </template>
        <span>列设置</span>
      </n-tooltip>
    </n-space>
    <!--  数据表格  -->
    <n-data-table
        :columns="columns"
        :data="data"
        :size="densityValue"
        :loading="loading"
        :pagination="pagination"
        :bordered="false"
        :row-key="rowKey"
        default-expand-all
    />
  </n-card>
  <!--  新建模态框  -->
  <n-modal v-model:show="showModal" preset="card" :style="bodyStyle" title="添加" :segmented="segmented">
    <!--  表单  -->
    <n-form :rules="rules" :model="formValue">
      <n-form-item label="岗位名称" path="user.name">
        <n-input
            v-model:value="formValue.user.name"
            placeholder="请输入岗位名称"
            clearable
        >
        </n-input>
      </n-form-item>
    </n-form>
    <template #footer>
      <n-space justify="end">
        <n-button @click="cancel">取消</n-button>
        <n-button type="info" @click="sure">确定</n-button>
      </n-space>
    </template>
  </n-modal>

  <!-- 新建子类模态框  -->
  <n-modal v-model:show="showModal1" preset="card" :style="bodyStyle" title="编辑" :segmented="segmented">
    <!--  表单  -->
    <n-form :rules="rules1" :model="formValue1">
      <n-form-item label="岗位名称" path="user.name">
        <n-input
            v-model:value="formValue1.user.name"
            placeholder="请输入岗位名称"
            clearable
        >
        </n-input>
      </n-form-item>
    </n-form>
    <template #footer>
      <n-space justify="end">
        <n-button @click="cancel1">取消</n-button>
        <n-button type="info" @click="sure1">确定</n-button>
      </n-space>
    </template>
  </n-modal>

  <!--  编辑模态框  -->
  <n-modal v-model:show="showEditModal" preset="card" :style="bodyStyle" title="编辑" :segmented="segmented">
    <!--  表单  -->
    <n-form :rules="rulesEdit" :model="formEditValue">
      <n-form-item path="user.name" label="岗位名称">
        <n-input
            v-model:value = "formEditValue.user.name"
            clearable
            placeholder="请输入岗位名称"
        >
        </n-input>
      </n-form-item>
    </n-form>
    <template #footer>
      <n-space justify="end">
        <n-button @click="cancelEdit">取消</n-button>
        <n-button type="info" @click="sureEdit">确定</n-button>
      </n-space>
    </template>
  </n-modal>
</template>



<script>
import { defineComponent, h, ref, reactive } from "vue";
import { NButton, NForm, NFormItem, NInput, NFlex, NIcon } from "naive-ui"
import {Add} from "@vicons/ionicons5";
import {RefreshSharp} from "@vicons/material";
import {AutoFitHeight20Regular, Settings20Regular} from "@vicons/fluent";
import {LeftOutlined, RightOutlined} from "@vicons/antd";
import { GetPosition, AddPosition, RenewPosition, DeletePosition } from "@/api/position";

export default defineComponent({
  components: {
    Add,
    RefreshSharp,
    AutoFitHeight20Regular,
    Settings20Regular,
    LeftOutlined,
    RightOutlined
  },

  setup() {
    const message = window.$message
    const dialog = window.$dialog
    // 加载
    const loading = ref(false)

    //数据表格
    // 创建表格列模板
    const createColumns = () => {
      return [
        {
          title: "序号",
          key: "index", /* | "indexx" | "indexxx" */
          /*
          children:[
            {
              key:"index1",
              children:[
                {
                  key:"index2",
                  render(row, index) {
                    return index + 1;
                  }
                }
              ],
              render(row, index) {
                return index + 1;
              }
            }
          ],
          */
          // render(row, index) {
          //     return index + 1;
          // }
        },
        {
          title: "用户名",
          key: "name",
        },
        {
          title: "创建时间",
          key: "time",
        },
        {
          title: "操作",
          key: "actions",
          render(row) {
            // console.log(row)
            switch (row.actions) {
                // 层级为0
              case 0:
                switch (row.isChildren){
                    // 新增子类 / 编辑
                  case 1:
                    return h(
                        NFlex,
                        {
                          size: "small",
                        },
                        {
                          default: () => [
                            h(
                                NButton,
                                {
                                  text: true,
                                  color: "#3FA2FE",
                                  onClick: () => {
                                    showModal1.value = true
                                    addPid.value = row.id
                                  }
                                },
                                { default: () => "新增子类" }
                            ),
                            h(
                                NButton,
                                {
                                  text: true,
                                  color: "#3FA2FE",
                                  onClick: () => {
                                    showEditModal.value = true
                                    formEditValue.value.user.name = row.name
                                    editId.value = row.id
                                  }
                                },
                                { default: () => "编辑" }
                            )
                          ]
                        }
                    )
                    // 新增子类 / 编辑 / 删除
                  case 0:
                    return h(
                        NFlex,
                        {
                          size: "small",
                        },
                        {
                          default: () => [
                            h(
                                NButton,
                                {
                                  text: true,
                                  color: "#3FA2FE",
                                  onClick: () => {
                                    showModal1.value = true
                                    addPid.value = row.id
                                  }
                                },
                                { default: () => "新增子类" }
                            ),
                            h(
                                NButton,
                                {
                                  text: true,
                                  color: "#3FA2FE",
                                  onClick: () => {
                                    showEditModal.value = true
                                    formEditValue.value.user.name = row.name
                                    editId.value = row.id
                                  }
                                },
                                { default: () => "编辑" }
                            ),
                            h(
                                NButton,
                                {
                                  text: true,
                                  color: "#3FA2FE",
                                  onClick: () => {
                                    dialog.warning({
                                      title: "删除",
                                      content: '确定删除吗？',
                                      positiveText: '确定',
                                      negativeText: '取消',
                                      maskClosable: false,
                                      onNegativeClick: () => {
                                        message.success('取消删除')
                                      },
                                      onPositiveClick: () => {
                                        message.success('确定删除')

                                        let getData = () => {
                                          let per_page = ref(100)
                                          const param = {
                                            page:page.value,
                                            per_page:per_page.value
                                          }
                                          GetPosition(param).then(j => {
                                            const content = j.data.list
                                            console.log(content)
                                            content.forEach((item) => {
                                              if(item.name === row.name){
                                                row.id = item.id
                                                DeletePosition(row.id).then(res => {
                                                  if (res.code === 0){
                                                    message.success(res.message)
                                                    // 更新数据
                                                    window.location.reload()
                                                  } else {
                                                    message.error(res.message)
                                                  }
                                                })
                                              }
                                            })
                                          })
                                        }
                                        // 调用
                                        getData()

                                      }
                                    })
                                  }
                                },
                                { default: () => "删除" }
                            )
                          ]
                        }
                    )
                }
                // 层级为1
              case 1:
                switch (row.isChildren){
                    // 新增子类 / 编辑
                  case 1:
                    return h(
                        NFlex,
                        {
                          size: "small",
                        },
                        {
                          default: () => [
                            h(
                                NButton,
                                {
                                  text: true,
                                  color: "#3FA2FE",
                                  onClick: () => {
                                    showModal1.value = true
                                    addPid.value = row.id
                                  }
                                },
                                { default: () => "新增子类" }
                            ),
                            h(
                                NButton,
                                {
                                  text: true,
                                  color: "#3FA2FE",
                                  onClick: () => {
                                    showEditModal.value = true
                                    formEditValue.value.user.name = row.name
                                    editId.value = row.id
                                  }
                                },
                                { default: () => "编辑" }
                            )
                          ]
                        }
                    )
                    // 新增子类 / 编辑 / 删除
                  case 0:
                    return h(
                        NFlex,
                        {
                          size: "small",
                        },
                        {
                          default: () => [
                            h(
                                NButton,
                                {
                                  text: true,
                                  color: "#3FA2FE",
                                  onClick: () => {
                                    showModal1.value = true
                                    addPid.value = row.id
                                  }
                                },
                                { default: () => "新增子类" }
                            ),
                            h(
                                NButton,
                                {
                                  text: true,
                                  color: "#3FA2FE",
                                  onClick: () => {
                                    showEditModal.value = true
                                    formEditValue.value.user.name = row.name
                                    editId.value = row.id
                                  }
                                },
                                { default: () => "编辑" }
                            ),
                            h(
                                NButton,
                                {
                                  text: true,
                                  color: "#3FA2FE",
                                  onClick: () => {
                                    dialog.warning({
                                      title: "删除",
                                      content: '确定删除吗？',
                                      positiveText: '确定',
                                      negativeText: '取消',
                                      maskClosable: false,
                                      onNegativeClick: () => {
                                        message.success('取消删除')
                                      },
                                      onPositiveClick: () => {
                                        message.success('确定删除')

                                        let getData = () => {
                                          let per_page = ref(100)
                                          const param = {
                                            page:page.value,
                                            per_page:per_page.value
                                          }
                                          GetPosition(param).then(j => {
                                            const content = j.data.list
                                            console.log(content)
                                            content.forEach((item) => {
                                              if(item.name === row.name){
                                                row.id = item.id
                                                DeletePosition(row.id).then(res => {
                                                  if (res.code === 0){
                                                    message.success(res.message)
                                                    // 更新数据
                                                    window.location.reload()
                                                  } else {
                                                    message.error(res.message)
                                                  }
                                                })
                                              }
                                            })
                                          })
                                        }
                                        // 调用
                                        getData()

                                      }
                                    })
                                  }
                                },
                                { default: () => "删除" }
                            )
                          ]
                        }
                    )
                }
                // 层级为2 （编辑 / 删除）
              case 2:
                return h(
                    NFlex,
                    {
                      size: "small",
                    },
                    {
                      default: () => [
                        h(
                            NButton,
                            {
                              text: true,
                              color: "#3FA2FE",
                              onClick: () => {
                                showEditModal.value = true
                                formEditValue.value.user.name = row.name
                                editId.value = row.id
                              }
                            },
                            { default: () => "编辑" }
                        ),
                        h(
                            NButton,
                            {
                              text: true,
                              color: "#3FA2FE",
                              onClick: () => {
                                dialog.warning({
                                  title: "删除",
                                  content: '确定删除吗？',
                                  positiveText: '确定',
                                  negativeText: '取消',
                                  maskClosable: false,
                                  onNegativeClick: () => {
                                    message.success('取消删除')
                                  },
                                  onPositiveClick: () => {
                                    message.success('确定删除')

                                    let getData = () => {
                                      let per_page = ref(100)
                                      const param = {
                                        page:page.value,
                                        per_page:per_page.value
                                      }
                                      GetPosition(param).then(j => {
                                        const content = j.data.list
                                        console.log(content)
                                        content.forEach((item) => {
                                          if(item.name === row.name){
                                            row.id = item.id
                                            DeletePosition(row.id).then(res => {
                                              if (res.code === 0){
                                                message.success(res.message)
                                                // 更新数据
                                                window.location.reload()
                                              } else {
                                                message.error(res.message)
                                              }
                                            })
                                          }
                                        })
                                      })
                                    }
                                    // 调用
                                    getData()

                                  }
                                })
                              }
                            },
                            { default: () => "删除" }
                        )
                      ]
                    }
                )
            }
          }
        }
      ]
    };
    // 调用列模板
    let columns = createColumns()
    // 表格数据
    let data = reactive([])
    // 总条数
    const total = ref(0);
    // 总页数
    const totalPage = ref(0);
    // 当前页
    const page = ref(0);
    // 分页设置
    const pagination = {
      prev:()=>{
        return h(
            NIcon,
            {
              onClick:()=>{
                if (page.value > 1) {
                  page.value --
                }
              }
            },
            {
              default: () => h(LeftOutlined)
            }
        )
      },
      next:()=>{
        return h(
            NIcon,
            {
              onClick:()=>{
                // console.log(lastPage.value)
                if (page.value < totalPage.value) {
                  // if (page.value === lastPage.value){
                  page.value ++
                  // getData(loading.value)
                  // }
                }
              }
            },
            {
              default: () => h(RightOutlined)
            }
        )
      },
      prefix:()=>{
        const range = [page.value * 10 - 9, page.value * 10];
        if (page.value === 0) {
          return `第 0 - 0 条 / 总共 ${total.value} 条`
        }else if (page.value === 1 && totalPage.value !== 1) {
          return `第 1 - ${range[1]} 条 / 总共 ${total.value} 条`;
        }else if (page.value === totalPage.value) {
          return `第 ${range[0]} - ${data.length} 条 / 总共 ${total.value} 条`;
        }else if (page.value > 1 && page.value < totalPage.value) {
          return `第 ${range[0]} - ${range[1]} 条 / 总共 ${total.value} 条`;
        }
      },
    }

    /*获取用户列表数据*/
    let getData = ()=>{
      let per_page = ref(100)
      const param = {
        page:page.value,
        per_page:per_page.value
      }
      loading.value = true
      GetPosition(param).then(res => {
        const content = res.data.list
        // console.log(content)
        // 转换数据库时间格式为标准时间格式方法
        let getDate = (time)=> {
          const dateTime = new Date(time)
          const year = dateTime.getFullYear()
          let month = (dateTime.getMonth() + 1)
          month =  month >= 10 ? month: `0${month}`
          let date = dateTime.getDate()
          date = date >= 10? date : `0${date}`
          let hour = dateTime.getHours()
          hour = hour >= 10? hour : `0${hour}`
          let minute = dateTime.getMinutes()
          minute = minute >= 10? minute : `0${minute}`
          let second = dateTime.getSeconds()
          second = second >= 10? second : `0${second}`
          return `${year}-${month}-${date} ${hour}:${minute}:${second}`
        }
        // 遍历数据库数据
        //将 level=0 的 添加到data中
        content.forEach((item) => {
          if (item.level === 0){
            data.push({
              // index: index,
              id:item.id,
              level:item.level,
              name:item.name,
              time:getDate(item.createdAt),
              actions: item.level,
              isChildren:0
            })
          }
        })
        console.log(data)
        // 将 level=1 的 添加到 data 的中
        content.forEach((item) => {
          if (item.level === 1){
            data.forEach(i =>{
              if (i.id === item.pid){
                i.isChildren = 1
                i.children = [{
                  // index: index1,
                  id:item.id,
                  pid:item.pid,
                  level:item.level,
                  name:item.name,
                  actions: item.level,
                  time:getDate(item.createdAt),
                  children:[],
                  isChildren:0
                }]
              }
            })
          }
        })
        console.log(data)
        // 将 level=2 的 添加到 data 的中
        content.forEach((item) => {
          if (item.level === 2){
            data.forEach(i => {
              if (i.children && i.children[0].id === item.pid){
                i.children[0].isChildren = 1
                i.children[0].children.push({
                  // index: index2,
                  id:item.id,
                  pid:item.pid,
                  level:item.level,
                  name:item.name,
                  actions: item.level,
                  time:getDate(item.createdAt),
                  isChildren:0
                })
              }
            })
          }
        })
        // 查看数据
        console.log(data)

        // 做一个循环，让每一组里边按从 1 开始的顺序排列
        for(let i=0; i< data.length; i++){

          data[i]['index'] = i+1
          let tempLevel2 = data[i].children;
          if (tempLevel2) {
            for (let j = 0; j < tempLevel2.length; j++) {
              tempLevel2[j]['indexx'] = j+1;

              let tempLevel3 = tempLevel2[j].children;
              if (tempLevel3) {
                for (let k = 0; k < tempLevel3.length; k ++) {
                  tempLevel3[k]['index'] = k + 1;
                }
              }
              // console.log(tempLevel2[j],'00000')
            }
          }
          // console.log(data[i])
        }
        total.value = res.meta.total
        // totalPage.value = Math.ceil(total.value / 10)
        totalPage.value = Math.ceil(data.length / 10)
        // lastPage.value = Math.ceil(data.length / 10)
        page.value = 1
        loading.value = false
      })
    }
    // 调用数据
    getData()

    /*  工具栏  */
    // 模态框
    /* 新建,编辑 */
    // 显示新建-模态框
    const showModal = ref(false)
    // 显示新建子类-模态框
    const showModal1 = ref(false)
    // 显示编辑-模态框
    const showEditModal = ref(false)
    // 模态框的样式
    const bodyStyle = {
      width: "640px",
    }
    const segmented = {
      content: "soft",
      footer: "soft",
    }
    // 取消新建-模态框
    function cancel() {
      showModal.value = false
    }
    // 取消新建子类-模态框
    function cancel1() {
      showModal1.value = false
    }
    // 取消编辑-模态框
    function cancelEdit() {
      showEditModal.value = false
    }

    // 新建-确定提交
    function sure() {
      let formData = {
        name: formValue.value.user.name,
      }
      // 添加到数据库
      AddPosition(formData).then(res => {
        if (res.code === 0) {
          message.success(res.message)
          cancel()
          // 刷新数据
          // window.location.reload()
        }else{
          message.error(res.message)
        }
      })
    }



    // 新建子类-addPid
    let addPid = ref()
    // 新建子类-确定提交
    function sure1() {
      let formData = {
        name: formValue1.value.user.name,
        pid: addPid.value,
      }
      // 添加到数据库
      AddPosition(formData).then(res => {
        // console.log(res)
        if (res.code === 0) {
          message.success(res.message)
          cancel1()
          // window.location.reload()
        } else {
          message.error(res.message)
        }
      })
    }



    // 编辑-id
    let editId = ref()
    // 编辑-确定提交
    function sureEdit() {
      let formData = {
        name: formEditValue.value.user.name,
        id: editId.value,
      }
      // 把更新的添加到数据库
      RenewPosition(formData).then(res => {
        // console.log(res)
        if (res.code === 0){
          message.success(res.message)
          window.location.reload()
        }else{
          message.error(res.message)
        }
      })
      showEditModal.value = false
    }


    // 新建-表单信息
    const formValue = ref({
      user: {
        name: "",
      }
    })


    // 新建子类-表单信息
    const formValue1 = ref({
      user: {
        name: "",
      }
    })


    // 编辑-表单信息
    const formEditValue = ref({
      user: {
        name: "",
      }
    })

    // 新建验证规则
    const rules = {
      user: {
        name: {
          required: true,
          trigger: "blur",
          message: "请输入岗位名称!"
        },
      }
    }
    // 新建验证规则
    const rules1 = {
      user: {
        name: {
          required: true,
          trigger: "blur",
          message: "请输入岗位名称!"
        },
      }
    }
    // 编辑验证规则
    const rulesEdit = {
      user: {
        name: {
          required: true,
          trigger: "blur",
          message: "请输入岗位名称!"
        }
      }
    }


    /*刷新*/
    //刷新
    function refresh() {
      window.location.reload()
    }
    // 密度
    // 密度事件数据
    const densityOptions = [
      {
        label: "默认",
        value: "large"
      },
      {
        label: "中等",
        value: "medium"
      },
      {
        label: "紧密",
        value: "small"
      }
    ]
    // 默认密度
    const densityValue = ref('medium')

    /* 列设置 */
    // 复选框全选
    const allChecked = ref(true)
    // 复选框列表
    const checkboxList = ref([])
    // 列表添加数据
    for (let i = 0; i < columns.length; i++){
      checkboxList.value.push({name: columns[i].title, checked: true})
    }
    // 全选改变事件
    const allChange = () =>{
      if (allChecked.value) {
        checkboxList.value.forEach(item => {item.checked = true})
      } else {
        checkboxList.value.forEach(item => {item.checked = false})
      }
    }
    // 复选框单个改变事件
    const itemChange = () => {
      if (checkboxList.value.every(item => item.checked)) {
        allChecked.value = true
      } else {
        allChecked.value = false
      }
    }

    return {
      //模态框
      showModal,
      showModal1,
      showEditModal,
      bodyStyle,
      segmented,
      cancel,
      cancel1,
      cancelEdit,
      sure,
      sure1,
      sureEdit,
      formValue,
      formValue1,
      formEditValue,
      rules,
      rules1,
      rulesEdit,

      // 数据表格
      rowKey: (row) => row.index,
      densityOptions,
      densityValue,
      columns,
      data,
      page,
      pagination,
      loading,
      refresh,
      checkboxList,
      allChecked,
      allChange,
      itemChange,
      editId,
      // addPid,

    };
  }
})

</script>

<style>

</style>